import {Component, ElementRef, HostListener, OnDestroy, OnInit, Renderer2, ViewContainerRef, ViewEncapsulation} from '@angular/core';
import {AppService} from "../../../app.service";
import {GlobalEvent} from "../../../support/event.definition";
import {AppComponent} from "../../../app.component";
import {animate, state, style, transition, trigger} from "@angular/animations";

@Component({
  selector: '.ss-platform-modal-wraper',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss'],
  animations: [
    trigger("fade", [
      state("void", style({opacity: 0})),
      state("*", style({opacity: .7})),
      transition("void <=> *", animate(200))
    ])
  ],
  encapsulation: ViewEncapsulation.None,
})
export class ModalComponent implements OnInit, OnDestroy {

  parentComponent: any;

  constructor(private elementRef: ElementRef, private renderer: Renderer2, private $app: AppService, private appComponent: AppComponent, private viewContainerRef: ViewContainerRef) {
    this.parentComponent = viewContainerRef["_hostLView"][3][8].components[0];
  }

  close(callback?: Function): void {
    this.appComponent.destroyComponent(this.parentComponent)
    callback && callback();
  }

  submit(result): void {
    this.close(() => {
      this.parentComponent.sourceEventResolve(result);
    });
  }

  ngOnInit(): void {
    // setTimeout(() => {
    // this.$app.publish(GlobalEvent.ShowMaskGray)
    // });
    this.resize();
  }


  @HostListener("window:resize")
  resize(): void {
    let modalContainer = this.elementRef.nativeElement.querySelector(".ss-platform-modal") as HTMLDivElement;
    let top = Math.min(180, document.body.clientHeight / 2 - (modalContainer.clientHeight / 2));
    this.renderer.setStyle(modalContainer, "top", top + "px");
    this.renderer.setStyle(modalContainer, "left", (document.body.clientWidth / 2 - (modalContainer.clientWidth / 2)) + "px");
  }

  ngOnDestroy(): void {
    // this.$app.publish(GlobalEvent.HideMask);
  }

}
